# -*- coding: utf-8 -*- 

"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################  


import sys
#logger = logging.getLogger("peertool.default")
#logger.setLevel(logging.DEBUG)
#debug = logger.debug        

import cPickle
ptproblem = local_import('ptproblem',reload=True)
#ptproblem = local_import('dummyclass',reload=True)

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    response.flash = T('Welcome to PeerTool')
    return dict(message=T('Hello World'))


@auth.requires_login()
def data(): 
    return dict(form=crud())

def hazardous():
    """ 
    Show the "PeerTool May Be Hazardous To Your Career" page
    """ 
    return(dict(message=None))

    
@auth.requires_login()
def cloneproblem():
    """ Allows user to clone current problem """
    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))
    try:
        session.problemid = cloneProblem(problem)
    except ActivityLimitException:
        session.flash = "Creating too many new problems. Please slow down!"
        redirect(URL(r=request, c='default', f='index'))
    redirect(URL(r=request, c='editproblem', f='index'))
    
@auth.requires_login()
def newproblem():
    """ Allows user to create a new problem  """
    syn = PTCFG.synonyms
    description = "%s\n%s"%(P(str(T("New"))+" "+syn["Problem"]),P(str(T("Please replace the title and this text with a description of the problem (aka issue, situation, challenge, opportunity, ...) you wish to address."))))
    fields = [Field('description','text', length=1000, 
    requires=IS_NOT_EMPTY(),
    default=XML(description))]

    for k in syn:
        debug(k)
        if k[0].isupper(): continue             # skip Title versions 
        fields.append(Field(k,'string',length=15,
            requires=IS_NOT_EMPTY(),
            default=syn[k],
            )
        )

    form = SQLFORM.factory(*fields)
    if form.accepts(request.vars, session):
        response.flash = 'form accepted'
        fv=form.vars
        for k in syn:                           # uncapitalize user's entries
            if k[0].islower():
                fv[k] = fv[k.lower()]
        for k in syn:                           # make initial caps versions
            if k[0].isupper():
                fv[k] = fv[k.lower()].title()
        try:
            session.problemid = createProblem(fv)
        except ActivityLimitException:
            session.flash = "Creating too many new problems. Please slow down!"
            redirect(URL(r=request, c='default', f='index'))

        redirect(URL(r=request, c='editproblem', f='index'))
        
    elif form.errors:
        response.flash = 'form has errors'
    return dict(form=form, title=T("New"))

        
def rpxtoken():
    """ Future handler for rpx callbacks """
    return None


def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    session.problemid = None
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


